package com.zml.cruddemo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zml.cruddemo.dto.JsonResp;
import com.zml.cruddemo.entity.PageBean;
import com.zml.cruddemo.entity.User;
import com.zml.cruddemo.service.UserService;

@RestController
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/user", method = RequestMethod.GET)
	public JsonResp listAllUsers(@RequestParam(value="page") String page) {
		if (page == null || "".equals(page)) {
			page = "1";
		}
		int count = this.userService.getTotle();
		PageBean pageBean = new PageBean(Integer.parseInt(page), 3, count);
		// map中封装起始页和每页的记录
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("start", pageBean.getStart());
		map.put("pageSize", pageBean.getPageSize());
		List<User> users = userService.getList(map);
		if (users.isEmpty()) {
			return JsonResp.fail("No users!!");
		}
		pageBean.setData(users);
		return JsonResp.success(pageBean);
	}

	@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
	public JsonResp getUser(@PathVariable("id") int id) {
		User user = userService.getById(id);
		if (user == null) {
			return JsonResp.fail("User with id " + id + " not found");
		}
		return JsonResp.success(user);
	}

	@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
	public JsonResp deleteUser(@PathVariable("id") int id) {
		User user = userService.getById(id);
		if (user == null) {
			return JsonResp.fail("Unable to delete. User with id " + id + " not found");
		}
		userService.deleteUserById(id);
		return JsonResp.success();
	}

	@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
	public JsonResp updateUser(@PathVariable("id") int id, @RequestBody User user) {
		User currentUser = userService.getById(id);
		if (currentUser == null) {
			return JsonResp.fail("User with id " + id + " not found");
		}
		currentUser.setUserName(user.getUserName());
		currentUser.setPassWord(user.getPassWord());
		currentUser.setAge(user.getAge());
		userService.updateUser(currentUser);
		return JsonResp.success(currentUser);
	}

	@RequestMapping(value = "/user", method = RequestMethod.POST)
	public JsonResp createUser(@RequestBody User user) {

		if (userService.isUserExist(user)) {
			return JsonResp.fail("A User with name " + user.getUserName() + " already exist");
		}
		userService.saveUser(user);
		return JsonResp.success(user);
	}
}
